#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <sys/types.h>
#include <libutil.h>
#include <pwd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/ktrace.h>
#include <time.h>
#include "kdump.h"

void get_mode(int mode)
{
  int macro_type[] = 
    {
      S_IFIFO, S_IFCHR, S_IFDIR, S_IFBLK, S_IFREG, S_IFLNK, S_IFSOCK, 0
    };
  int i;
  char char_type[] = {'p', 'c', 'd', 'b', '-', 'l', 's', 0};

  i = 0;
  while (macro_type[i] != 0)
    {
      if ((mode & S_IFMT) == macro_type[i])
	{
	  printf("%c", char_type[i]);
	  break;
	}
      i++;
    }
}

void aff_droit(int mode)
{

  int i, j;
  int macro_perm[4][4] = 
    {
      {S_IRUSR, S_IWUSR, S_IXUSR, 0},
      {S_IRGRP, S_IWGRP, S_IXGRP, 0},
      {S_IROTH, S_IWOTH, S_IXOTH, 0},
      {0,0,0,0}
    };
  char char_perm[4][3] = 
    {
      "rwx",
      "rwx",
      "rwx",
      "0"
    };

  i = 0;
  get_mode(mode);
  while (macro_perm[i][0] != 0)
    {
      j = 0;
      while (macro_perm[i][j] != 0)
        {
          if ((mode & macro_perm[i][j]) == macro_perm[i][j])
            printf("%c", char_perm[i][j]);
          else
            printf("-");
          j++;
        }
      i++;
    }
}

void			aff_time(time_t time, char *name)
{
  char*			buff;

  buff = ctime(&time);
  buff[strlen(buff) - 1] = '\0';
  printf(" %s=\"%s\" ,", name, buff);
}

void			aff_r(struct stat s)
{
  struct passwd		*pwd;
  struct group		*group;

  pwd = getpwuid(s.st_uid);
  group = getgrgid(s.st_gid);
  printf("uid=\"%s\", gid=\"%s\", rdev=%d," , pwd->pw_name, group->gr_name, s.st_rdev);
  aff_time(s.st_atime, "atime");
  aff_time(s.st_mtime, "stime");
  aff_time(s.st_ctime, "ctime");
  aff_time(s.st_mtime, "birthtime");
}

void			print_stat(struct stat s, t_args* args)
{
  printf("struct stat {");
  printf("dev=%d, ino=%d, mode=", s.st_dev, s.st_ino);
  aff_droit(s.st_mode);
  printf(" , nlink=%d, ", s.st_nlink);
  if (!args->r)
    {
      printf("uid=%d, gid=%d, rdev=%d, atime=%d, ", s.st_uid, s.st_gid, s.st_rdev, s.st_atime);
      printf("stime=%d, ctime=%d, birthtime=%d, ", s.st_mtime, s.st_ctime, s.st_mtime);
    }
  else
    aff_r(s);
  printf("size=%d, blksize=%d, blocks=%d", (int)s.st_size, (int)s.st_blksize, (int)s.st_blocks);
  printf(", flag=0x%x }", s.st_flags);
}
